<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青云教育系统 - 教师端</title>
    <link rel="stylesheet" href="../../teacher.css">
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="brand">青云教育 · 教师端</div>
            <nav class="menu" id="menu">
                <button class="menu-item" data-view="profile" data-url="/index">教员信息及考勤</button>
                <button class="menu-item" data-view="schedule" data-url="/schedule">教师课表</button>
                <button class="menu-item" data-view="password" data-url="/password">修改密码</button>
                <button class="menu-item" data-view="students" data-url="/students">学生信息</button>
                <button class="menu-item active" data-view="upload" data-url="/postmaterial">上传资料</button>
                <button class="menu-item" data-view="download" data-url="/download">下载资料</button>
                <button class="menu-item" data-view="mymaterials" data-url="/mymaterials">我的资料</button>
            </nav>
        </aside>
        <main class="content">
            <header class="topbar">
                <div class="left">
                    <h1 id="view-title">上传资料</h1>
                </div>
                <div class="right">
                    <div class="user-info">
                        <img id="user-avatar" class="user-avatar" src="" alt="用户头像">
                        <span id="teacher-name" class="user-name"></span>
                    </div>
                    <button id="logoutBtn" class="btn btn-secondary">退出登录</button>
                </div>
            </header>

            <section id="view-upload" class="view" style="display:block;">
                <!-- 上传资料表单 -->
                <div class="card">
                    <div class="card-header">上传新资料</div>
                    <div class="card-body">
                        <form id="uploadForm" class="form upload-grid">
                            <div class="form-group span-2">
                                <label>资料标题 <span class="required">*</span></label>
                                <input type="text" id="materialTitle" placeholder="请输入资料标题" required>
                            </div>
                            <div class="form-group span-2">
                                <label>资料描述</label>
                                <textarea id="materialDescription" placeholder="请输入资料描述（可选）" rows="3"></textarea>
                            </div>
                            <div class="form-group span-2">
                                <label>选择文件 <span class="required">*</span></label>
                                <input type="file" id="materialFile" accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar" required>
                                <div class="file-info">
                                    <small>支持格式：PDF、Word、PPT、Excel、TXT、ZIP、RAR</small>
                                    <small>最大文件大小：50MB</small>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>资料分类</label>
                                <select id="materialCategory">
                                    <option value="">请选择分类</option>
                                    <option value="课件PPT">课件PPT</option>
                                    <option value="习题PDF/DOCX">习题PDF/DOCX</option>
                                    <option value="讲义PDF/DOCX">讲义PDF/DOCX</option>
                                    <option value="试卷PDF/DOCX">试卷PDF/DOCX</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>适用年级</label>
                                <select id="materialGrade">
                                    <option value="">请选择年级</option>
                                    <option value="高一">高一</option>
                                    <option value="高二">高二</option>
                                    <option value="高三">高三</option>
                                    <option value="通用">通用</option>
                                </select>
                            </div>
                            <div class="form-group span-2">
                                <label>适用科目</label>
                                <select id="materialSubject">
                                    <option value="">请选择科目</option>
                                    <option value="数学">数学</option>
                                    <option value="语文">语文</option>
                                    <option value="英语">英语</option>
                                    <option value="物理">物理</option>
                                    <option value="化学">化学</option>
                                    <option value="生物">生物</option>
                                    <option value="历史">历史</option>
                                    <option value="地理">地理</option>
                                    <option value="政治">政治</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                            <div class="form-actions span-2">
                                <button type="submit" class="btn btn-primary">上传资料</button>
                                <button type="reset" class="btn btn-secondary">重置</button>
                            </div>
                            <div id="uploadMsg" class="message" style="display:none;"></div>
                        </form>
                    </div>
                </div>

            </section>
        </main>
    </div>

    <script src="../../teacher.js"></script>
    <script>
        // 确保退出登录功能正常工作
        document.addEventListener('DOMContentLoaded', function(){
            // 绑定退出登录按钮事件
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn && !logoutBtn.hasAttribute('data-bound')) {
                logoutBtn.setAttribute('data-bound', 'true');
                logoutBtn.addEventListener('click', function(e) {
                    console.log('退出登录按钮被点击（来自postmaterial页面）');
                    e.preventDefault();
                    if (typeof logout === 'function') {
                        logout();
                    } else {
                        console.error('logout函数未定义');
                    }
                });
            }
            
            // 菜单跳转逻辑
            const menu = document.getElementById('menu');
            menu.addEventListener('click', function(e){
                const btn = e.target.closest('.menu-item');
                if(!btn) return;
                const view = btn.getAttribute('data-view');
                if(view === 'schedule') window.location.href = location.origin + '/teacher/schedule';
                else if(view === 'password') window.location.href = location.origin + '/teacher/password';
                else if(view === 'profile') window.location.href = '/index.html';
                else if(view === 'students') window.location.href = location.origin + '/teacher/students';
                else if(view === 'upload') window.location.href = location.origin + '/teacher/postmaterial';
                else if(view === 'download') window.location.href = location.origin + '/teacher/downloadmaterial';
                else if(view === 'mymaterials') window.location.href = location.origin + '/teacher/mymaterials/';
            });
            
            // 绑定上传表单事件
            bindUploadForm();
            

        });

        // 绑定上传表单
        function bindUploadForm() {
            const form = document.getElementById('uploadForm');
            const msg = document.getElementById('uploadMsg');
            
            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const title = document.getElementById('materialTitle').value.trim();
                const description = document.getElementById('materialDescription').value.trim();
                const fileInput = document.getElementById('materialFile');
                const category = document.getElementById('materialCategory').value;
                const grade = document.getElementById('materialGrade').value;
                const subject = document.getElementById('materialSubject').value;
                
                // 表单验证
                if (!title) {
                    showMsg(msg, '请输入资料标题', 'error');
                    return;
                }
                
                if (!fileInput.files.length) {
                    showMsg(msg, '请选择要上传的文件', 'error');
                    return;
                }
                
                const file = fileInput.files[0];
                if (file.size > 50 * 1024 * 1024) { // 50MB
                    showMsg(msg, '文件大小不能超过50MB', 'error');
                    return;
                }
                
                                 // 显示上传中状态
                 const submitBtn = form.querySelector('button[type="submit"]');
                 const originalText = submitBtn.textContent;
                 submitBtn.disabled = true;
                 submitBtn.textContent = '上传中...';
                 
                 try {
                     // 创建FormData对象
                     const formData = new FormData();
                     formData.append('title', title);
                     formData.append('description', description);
                     formData.append('file', file);
                     formData.append('category', category);
                     formData.append('grade', grade);
                     formData.append('subject', subject);
                     
                     // 调用上传接口
                     const response = await fetch('/material/upload', {
                         method: 'POST',
                         headers: {
                             'Authorization': JSON.parse(localStorage.getItem('userInfo') || '{}').token || ''
                         },
                         body: formData
                     });
                     
                     if (!response.ok) {
                         const errorText = await response.text();
                         throw new Error(errorText || `上传失败: ${response.status}`);
                     }
                     
                     const result = await response.json();
                     console.log('后端响应:', result); // 添加调试日志
                     
                     // 修改判断条件，适配后端返回格式
                     if (result.success === true || result.code === 200) {
                         showMsg(msg, '资料上传成功！', 'success');
                         form.reset();
                     } else {
                         throw new Error(result.message || result.errorMsg || '上传失败');
                     }
                     
                 } catch (error) {
                     console.error('上传失败:', error);
                     showMsg(msg, '上传失败：' + error.message, 'error');
                 } finally {
                     // 恢复按钮状态
                     const submitBtn = form.querySelector('button[type="submit"]');
                     submitBtn.disabled = false;
                     submitBtn.textContent = originalText;
                 }
            });
        }









        // 消息提示函数
        function showMsg(el, msg, type='info'){
            if (!el) {
                console.error('消息元素不存在');
                return;
            }
            el.textContent = msg;
            el.className = `message ${type}`;
            el.style.display = 'block';
            setTimeout(()=>{ el.style.display='none'; }, 4000);
            console.log('显示消息:', msg, '类型:', type);
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知时间';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
        }
    </script>
</body>
</html>
